package teshop.data.dao.jpa;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import teshop.data.dao.GeneralDAO;


/**
 * JPA implementation of generic DAO
 * 
 * @author Hryhory Lira
 *
 * @param <Type> an object
 * @param <ID> unique id
 */
@Transactional
public class JPAGeneralDAO<Type, ID extends Serializable> implements
		GeneralDAO<Type, ID> {
	
	@PersistenceContext
	protected EntityManager manager;
	
	protected Logger logger = Logger.getLogger(JPAGeneralDAO.class);
	
	private Class<Type> persistentClass;

	@SuppressWarnings("unchecked")
	public JPAGeneralDAO() {
		this.persistentClass = (Class) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@Override
	public void delete(Type object) {
		logger.info(new Date() + " Deleting object: " + object.getClass());
		manager.remove(object);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Type> getAll() {
		logger.info(new Date() + "############## Selecting object: ");
		return manager.createQuery("SELECT t from " + 
				persistentClass.getSimpleName() + " t").getResultList();
	}

	@Override
	public Type getByID(Serializable id) {
		logger.info(new Date() + " Getting object");
		return manager.find(persistentClass, id);
	}

	@Override
	public void save(Type object) {
		logger.info(new Date() + "############## Persisting object: " + object.getClass());
		manager.persist(object);
	}

	@Override
	public void update(Type object) {
		logger.info(new Date() + " Updating object: " + object.getClass());
		manager.merge(object);
	}

}
